<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Admin extends MY_Controller {

	protected $restricted_to_admin = true;
	private $salt;
	private $matchgroup = 1;
	private $matchgroups;
	private $now;

	
	function Admin() {
        parent::MY_Controller();

        $this->now = date("Y-m-d H:i:s");

        $this->ci =& get_instance();

        $this->salt = $this->ci->config->item('encryption_key');
		
		$sql = "SELECT DISTINCT matchgroup FROM ". $this->tblm;
		$query = $this->db->query($sql);
		$this->matchgroups = $query->result();

		$sql = "SELECT matchgroup, deadline FROM ".$this->tblm." WHERE deadline > ? ORDER BY deadline ASC LIMIT 1";
		$query = $this->db->query($sql, array($this->now));

		if ($query->num_rows() > 0) {
			$res = $query->result();
			$this->matchgroup = $res[0]->matchgroup;
		} else
			$this->matchgroup = $this->matchgroups[0]->matchgroup;

	}

	function index() {
		$data = $this->getData('admin');
		$data['agoto'] = "admin";
		$data['content'] = $this->matches($this->matchgroup);
		$this->load->view('layout', $data);
	}

	function matchgroup($mg) {
		$this->matchgroup = $mg;
		return $this->index();
	}

	function useredit() {
		$data = $this->getData('admin');
		$data['agoto'] = "useredit";
		
		$d = $this->getUser(null);
		$data['content'] = $this->load->view('admin/useredit', $d, true);
		$this->load->view('layout', $data);
	}
	
	function configuration() {
		$data = $this->getData('admin');
		$data['agoto'] = "configuration";
		
		$sql = "SELECT name, typ, val FROM ".$this->tblc." ORDER BY name";
		$query = $this->db->query($sql);
		
		foreach($query->result() as $entry) {
			$tmp = array();
			$tmp[] = $entry->name;
			$tmp[] = $entry->typ;
			if ($entry->typ === "string") {
				$tmp[] = $entry->val;
			}
			else if ($entry->typ === "arr") {
				$tmp[] = $this->generatetextareaStringFromArray($entry->val);
			}
			else {
				$tmp[] = $this->generatetextareaStringFromObj($entry->val);
			}
			$result[] = $tmp;
		}

		$data['content'] = $this->load->view('admin/configuration', array("entries" => $result), true);
		$this->load->view('layout', $data);
	}
	
	function newsletter() {
		$data = $this->getData('admin');
		$data['agoto'] = "newsletter";
		
		$data['content'] = $this->load->view('admin/newsletter', null, true);
		$this->load->view('layout', $data);
	}
	
	function sendnewsletter() {
		$subject = $this->input->post('subject');
		$message = $this->input->post('message');

		if (strlen($message) > 0 && strlen($subject) > 0) { 		
			$this->ci =& get_instance();

			$d = $this->getUser(null);
			$count = 0;
			foreach($d['user'] as $u) {
				$this->email->from($this->ci->config->item('admin_email'), $this->ci->config->item('admin_name'));
				$this->email->to($u->email);
				$this->email->subject($subject);
				$this->email->message($message);
				$this->email->send();
				$count++;
			}
			$status = "Newsletter an $count Emailadressen gesendet.";
		}
		else {
			$status = "No subject/message given.";
		}
		
		$flashdata['status'] = $status;
		$this->session->set_flashdata($flashdata);
		redirect("admin/newsletter");
	}

	private function matches($matchgroup) {

		$sql = "SELECT * FROM ".$this->tblm
			." WHERE matchgroup = ?"
			." ORDER BY deadline";
			
		$query = $this->db->query($sql,array($matchgroup));
		$d['matchgroups'] = $this->matchgroups;
		$d['matches'] = $query->result();

		return $this->load->view('admin/matches', $d, true);
	}

	function calculatePoints() {
		$group = $this->input->post('group');
		$ids = $this->input->post('id');
		$goals_h = $this->input->post('goals_h');
		$goals_a = $this->input->post('goals_a');
		if (sizeof($ids) === sizeof($goals_h) && sizeof($ids) === sizeof($goals_a)) {
		
			$i = 0;
			while( sizeof($ids) > $i) {
				$id = $ids[$i];
				$gh = $goals_h[$i];
				$ga = $goals_a[$i];
				if ( strlen($gh) > 0 && strlen($ga) > 0 ) {
					$arr = array($gh, $ga, $id);
					$sql = "UPDATE ".$this->tblm." SET goals_h = ?, goals_a = ? WHERE id = ?";
					$query = $this->db->query($sql, $arr);					
				}
				$i++;
			}
			
			$this->calculate($group);
			
			redirect("admin#matchtab".$group);
		}

		$data = $this->getData('admin');
		$data['content'] = "calculatePoints";
		$this->load->view('layout', $data);
	}
	
	
	function saveuser() {
	$userId = $this->input->post("id");
		$keys = array("name","email","username","groupname");

		$values = array();
		$sql = "UPDATE ".$this->tblu." SET ";

		foreach($keys as $key) {
			$sql .= $key." = ?, ";
			$values[] = $this->input->post($key);
		}

		// password
		$password = $this->input->post("password");
		if (strlen($password) > 0) {

			$sql .= "hash = ?, password = ?, ";

			$hash = sha1(microtime());
			$password_enc = sha1($this->salt.$hash.$password);
			$values[] = $hash;
			$values[] = $password_enc;
		}		
		
		// settings
		$sql .= "settings = ? ";
		$settings = generateUserSettings(
			$this->input->post("url"),
			$this->input->post("messenger_type"),
			$this->input->post("messenger_value")
		);
		$values[] = json_encode($settings);

		// user id
		$sql .= " WHERE id = ? LIMIT 1";
		$values[] = $userId;

		// update now!
		$query = $this->db->query($sql, $values);

		$status  = "Die Benutzerdaten wurden gespeichert.";

		$flashdata['status'] = $status;
		$this->session->set_flashdata($flashdata);
		redirect("admin/useredit");
	}
	
	function loaduser() {
		$id = $this->input->post('id');
		$sql = "SELECT * FROM ".$this->tblu." WHERE id = ?";
		$query = $this->db->query($sql, array ($id));
		$res = $query->result();
		
		$u = json_decode($res[0]->settings);
		$u->id = $res[0]->id;
		$u->username = $res[0]->username;
		$u->name  = $res[0]->name;
		$u->email = $res[0]->email;
		$u->group = $res[0]->groupname;

		echo json_encode($u);
	}


	function editdate() {
		$id = $this->input->post('id');
		
		// remove 'date' from id string
		$id = str_replace("date", "", $id);
		$value = $this->input->post('value');

		$dateValue = date("Y-m-d H:i:s", strtotime($value));

		if (strlen($id) === 0) {
			$ret = 'ID missing.';
		} else if ($value !== $dateValue) {
			$ret = 'Wrong date format.';
		} else {
			$sql = "UPDATE ".$this->tblm." SET deadline = ? WHERE id = ?";
			$query = $this->db->query($sql, array ($value, $id));

			$ret = $value;
			
		}
		echo $ret;
	}

	
	function saveconfig() {

		$keys = $this->input->post('config_key');
		$types= $this->input->post('config_typ');
		$vals = $this->input->post('config_value');
		$this->db->trans_start();
		if (sizeof($keys) === sizeof($vals)) {
			$i = 0;
			while( sizeof($keys) > $i) {
				$key = $keys[$i];
				$typ = $types[$i];
				
				if ($typ === "string") {
					$value = $vals[$i];
				}
				else if ($typ === "arr") {
					$value = $this->generatejsonArrayString($vals[$i]);	
				}
				else {
					$value = $this->generatejsonObjString($vals[$i]);	
				}
				
				
				$sql = "UPDATE ".$this->tblc." SET val = ? WHERE name = ?";
				$query = $this->db->query($sql, array ($value, $key));
				$i++;
			}
		}
		$this->db->trans_complete();
		redirect("admin/configuration");		
	}

	private function generatejsonArrayString($str) {
		$result = array();
		// Erzeugt aus dem übergebenen String ein JSON-Array-String
		$rows = explode("\n", $str);
		foreach ($rows as $row) {
		$row = trim($row);
			if (strlen($row) > 0) {
				$attribs = explode(";", $row);
				if (sizeof($attribs) > 1) {
					// Der String kodiert mehrere Attribute
					$tmp = array();
					foreach ($attribs as $a) {
						$tmp[] = trim($a);
					}
					$result[] = $tmp;
				}
				else {
					// Der String besteht nicht aus mehreren Teilen
					$result[] = $row;	
				}
		}
		} // foraech
		return json_encode($result);
	}
	
	private function generatejsonObjString($str) {
		$result = new stdClass();
		$rows = explode("\n", $str);
		foreach ($rows as $row) {
			if (trim(strlen($row)) > 0) {
				$r = explode("=", $row);
				$key = trim($r[0]);
				$value = trim($r[1]);
				$result->$key = $value;
			}
		}
		return json_encode($result); 
	}	
	

	private function generatetextareaStringFromArray($str) {
		$res = "";
		if (strlen($str) > 0) {
			$tmp = json_decode($str);
			foreach ($tmp as $a) {
				if (is_string($a))
					$res .= $a."\n";
				else
					$res .= implode(";", $a)."\n";
			}
		}
		return $res;
	}
	
	private function generatetextareaStringFromObj($str) {
		$res = "";
		if (strlen($str) > 0) {
			$tmp = json_decode($str);
			foreach (get_object_vars($tmp) as $k => $v) {
				$res .= $k." = ".$v."\n";
			}
		}
		return $res;
	}

	
	
	private function calculate($group) {
		$eH = $this->tblm.".goals_h";
		$eA = $this->tblm.".goals_a";
		$tH = $this->tblt.".g_goals_h";
		$tA = $this->tblt.".g_goals_a";
		
		
		// Bisher eingetragene Punkte für den übergebenen Spieltag löschen
		$sql = "DELETE FROM ".$this->tblp." WHERE matchgroup = ?";
		$this->db->query($sql, array($group));

		$sql = "SELECT id, name FROM ".$this->tblu." ORDER BY name";
		$query = $this->db->query($sql);
		
		$sql = "SELECT"
			."($eH = $tH && $eA = $tA ) AS isPerfect,"
			."(($tH-$tA) =  ($eH-$eA)) AS isDiff,"
			."( ($tH < $tA && $eH < $eA)"
			."||($tH > $tA && $eH > $eA) ) AS isTendency"
		." FROM ".$this->tblm.", ".$this->tblt.""
			." WHERE ".$this->tblm.".matchgroup = ?"
			." AND ".$this->tblm.".id = ".$this->tblt.".match_id"
			." AND ".$this->tblt.".user_id = ?"
			." AND ".$this->tblm.".goals_h IS NOT NULL"
			." AND ".$this->tblm.".goals_a IS NOT NULL";

		$upd_sql = "INSERT INTO ".$this->tblp." (perfect, difference, tendency, wrong, user_id, matchgroup) VALUES (?, ?, ?, ?, ?, ?)";

		foreach($query->result() as $user) {
			$q = $this->db->query($sql, array($group, $user->id));
			
			$punkte = array(0, 0, 0, 0, $user->id, $group);
			foreach($q->result() as $result) {
				
				if ($result->isPerfect)
					$punkte[0]++;
				else if($result->isDiff)
					$punkte[1]++;
				else if($result->isTendency)
					$punkte[2]++;
				else
					$punkte[3]++;
					
			}

			$this->db->query($upd_sql, $punkte);
		}
	}
	   
}
?>
